package com.lzjt.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzjt.entity.DrugEntity;
import com.lzjt.mapper.DrugMapper;
import com.lzjt.model.DrugModel;
import com.lzjt.param.DrugParam;
import com.lzjt.util.Msg;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional

public class DrugService {
    @Autowired
    private DrugMapper drugMapper;
    public PageInfo<DrugModel> getDrugWithPage(int pn, int size, String name){
        PageHelper.startPage(pn,size);
        List<DrugModel> list=drugMapper.getAllDrug(name);
        PageInfo<DrugModel> info=new PageInfo<>(list,5);
        return info;
    }
    public Msg saveDrug(DrugParam drugParam){
        drugParam.setCreatetime(new Date());
        drugParam.setUpdatetime(new Date());
        int i=drugMapper.saveDrug(drugParam);
        int j=drugMapper.insertSalePlace(drugParam.getDrugId(),drugParam.getSaleIds());
        List<DrugModel> allDrug= drugMapper.getAllDrug(null);
        drugParam.setTotal((long)allDrug.size());
        if(i>0&&j>0){
            Long num=drugParam.getTotal()%5==0?(drugParam.getTotal()/5):(drugParam.getTotal()/5)+1;
            return Msg.success().data("pages",num).mess("添加成功");
        }
        return Msg.fail().mess("添加失败");
    }
    public Msg updateDrug(Long id,DrugParam drugParam){
        drugParam.setUpdatetime(new Date());
        drugParam.setDrugId(id);
        drugMapper.deleteSaleByDrugId(drugParam.getDrugId());
        drugMapper.insertSalePlace(drugParam.getDrugId(),drugParam.getSaleIds());
        DrugEntity drugEntity =new DrugEntity();
        BeanUtils.copyProperties(drugParam,drugEntity);
        int i=drugMapper.updateDrugById(drugEntity);
        if(i>0){
            return Msg.success().mess("修改成功");
        }
        return Msg.fail().mess("修改失败");
    }
    public Msg deleteDrug(Long drugId){
        int i=drugMapper.deleteDrugById(drugId);
        int j=drugMapper.deleteSaleByDrugId(drugId);
        if(i>0&&j>0){
            return Msg.success().mess("删除成功");
        }
        return Msg.fail().mess("删除失败");
    }
}
